//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.school.component.jwt;

import com.school.model.User;
import com.school.model.UserRole;
import com.school.service.impl.UserRoleServiceImpl;
import com.school.service.impl.UserServiceImpl;
import com.school.utils.IpUtil;
import com.school.utils.ResponseUtil;
import com.school.utils.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

@EnableConfigurationProperties({JwtProperties.class})
@ConditionalOnProperty(
        prefix = "jwt.config",
        name = {"enabled"}
)
@Configuration
public class JwtConfiguration {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserRoleServiceImpl userRoleService;

    @Bean
    public JwtTokenGenerator jwtTokenGenerator(JwtProperties jwtProperties) {
        return new JwtTokenGenerator(new JwtPayloadBuilder(), jwtProperties);
    }

    @Bean
    public AuthenticationSuccessHandler jsonAuthenticationSuccessHandler(JwtTokenGenerator jwtTokenGenerator) {
        return (request, response, authentication) -> {
            Map<String, Object> map = new HashMap();
            UserDetails principal = (UserDetails) authentication.getPrincipal();
            User user = this.userService.queryByUsername(principal.getUsername());
            List<UserRole> userRoles = this.userRoleService.queryByUserId(user.getId());
            if (userRoles.size() == 0) {
                throw new NullPointerException("该用户未设置角色!");
            } else {
                //-127~128
                HashSet<Integer> roleIds = new HashSet<>();
                for (UserRole userRole : userRoles) {
                    roleIds.add(userRole.getRoleId());
                }
                Integer level = (Integer) request.getAttribute("level");
                if (level == null) {
                    String level1 = request.getParameter("level");
                    Assert.notNull(level1, "用户角色无法识别！");
                    level = Integer.parseInt(level1);
                }
                if (!roleIds.contains(level)) {
                    String build = ResponseUtil.build(HttpStatus.BAD_GATEWAY.value(), "用户名登录错地方！");
                    ResponseUtil.printlnInfo(response, build);
                    return;
                } else {
                    if (user.getAccountStatus().equals(Status.LOGIN_NOT_ALLOWED)) {
                        String build = ResponseUtil.build(HttpStatus.BAD_GATEWAY.value(), "还没开始登录呢~");
                        ResponseUtil.printlnInfo(response, build);
                    }
                    user.setLastLoginIp(request.getRemoteAddr());
                    user.setLastLoginTime(LocalDateTime.now());
                    user.setLocation(IpUtil.retrieveCity(user.getLastLoginIp()));
                    user.setPassword((String) null);
                    this.userService.updateByIdSelective(user);
                    JwtTokenPair jwtTokenPair = jwtTokenGenerator.jwtTokenPair(principal.getUsername(), principal.getAuthorities(), (Map) null);
                    map.put("access_token", jwtTokenPair.getAccessToken());
                    map.put("refresh_token", jwtTokenPair.getRefreshToken());
                    String buildx = ResponseUtil.build(HttpStatus.OK.value(), "登录成功！", map);
                    ResponseUtil.printlnInfo(response, buildx);
                }
            }
        };
    }

    @Bean
    public AuthenticationFailureHandler jsonAuthenticationFailureHandler() {
        return (request, response, exception) -> {
            String build = ResponseUtil.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), exception.getMessage());
            ResponseUtil.printlnInfo(response, build);
        };
    }
}
